<?php
namespace Plu\Library\Services\Platform\Game;

use Plu\Library\Services\ServiceBase,
    Plu\Library\Models\Platform\Game\Category as CategoryModel,
    Plu\Library\Models\Platform\Tag\TagMap as TagMapModel,
    Plu\Library\Services\Redis\Tag\TagRedis;

class GamesService extends ServiceBase {
	private static $games = [];

	private static $gamesByTag = [];

	private static $gamesById = [];

    private static $initialized = false;

    const CACHE_TIME = 60;

	private static function _initialize($skin = 0) {
		if (self::$initialized) {
			return;
		}

        self::$gamesById = CategoryModel::getGames($skin);

		self::$games      = array_values(self::$gamesById);
		self::$gamesByTag = array_combine(array_column(self::$games, 'domain'), self::$games);

		self::$initialized = true;
	}

	/**
	 * 根据游戏ID获取信息
	 * @return array( 'id', 'name', 'tag')
	 */
	public static function getGameInfoById($gameId, $skin = 0) {
		self::_initialize($skin);

		return self::$gamesById[$gameId];
	}

	/**
	 * 根据游戏TAG获取信息
	 */
	public static function getGameInfoByTag($tag, $skin = 0) {
		self::_initialize($skin);
		return self::$gamesByTag[$tag];
	}

	/**
	 * 根据游戏TAG获取信息
	 */
	public static function getGameInfoByDomain($domain, $skin = 0) {
        return self::getGameInfoByTag($domain, $skin);
	}

	public static function getGames($skin = 0) {
		self::_initialize($skin);

		return self::$games;
    }

    public static function getGameIdsByTags($tags) {
        if (!is_array($tags)) {
            $tags = array($tags);
        }

        $tagRedis = new TagRedis;
        $tags = $tagRedis->validation($tags, TagMapModel::ITEM_TYPES['CATEGORY']);
        
        if (empty($tags)) {
            return [];
        }

        $guid = sprintf("gtags_%s", md5(json_encode($tags)));
        $cache_handler = self::getCacheHandler();
        $items = $cache_handler->get($guid);

        if ($items) {
            return $items;
        }

        $items = TagMapModel::getItemIdsByItemNames($tags, TagMapModel::ITEM_TYPES['CATEGORY']);
        $cache_handler->save($guid, $items, self::CACHE_TIME);

        return $items;
    }
}

?>
